package com.gz.steak.common.aspect;

import com.auth0.jwt.JWT;
import com.gz.steak.common.aspect.anotation.Auth;
import com.gz.steak.common.aspect.auth.Authority;
import com.gz.steak.common.exception.BusinessException;
import com.gz.steak.common.exception.EmBusinessError;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 *
 * @Author 刘牌
 * @Date 2020/3/13 0013 18:04
 * @Version 1.0
 */
@Component
@Aspect
public class SecurityAspect {
    private final static Logger logger = LoggerFactory.getLogger(SecurityAspect.class);
    @Autowired
    private HttpServletRequest request;

    @Pointcut("@annotation(auth)")
    public void pointcutPermission(Auth auth) {}

    @Around("pointcutPermission(auth)")
    public Object doPermission(ProceedingJoinPoint point, Auth auth) throws Throwable {
        String token = request.getHeader("token");
        List<String> roles = JWT.decode(token).getClaim("roles").asList(String.class);
        if (Authority.isContain(auth,roles)){
            return point.proceed();
        }
        else {
            throw new BusinessException(EmBusinessError.NO_AUTH);
        }
    }
}
